<template>
  <el-dialog
    v-model="visible"
    :title="title"
    width="800px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="120px"
    >
      <el-form-item label="用例名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入用例名称" />
      </el-form-item>

      <el-form-item label="所属项目" prop="project_id">
        <el-select v-model="formData.project_id" placeholder="请选择项目" style="width: 100%">
          <el-option
            v-for="project in projects"
            :key="project.id"
            :label="project.name"
            :value="project.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="请求方法" prop="method">
        <el-select v-model="formData.method" placeholder="请选择请求方法">
          <el-option label="GET" value="GET" />
          <el-option label="POST" value="POST" />
          <el-option label="PUT" value="PUT" />
          <el-option label="DELETE" value="DELETE" />
          <el-option label="PATCH" value="PATCH" />
        </el-select>
      </el-form-item>

      <el-form-item label="请求路径" prop="path">
        <el-input v-model="formData.path" placeholder="请输入请求路径，如：/api/users" />
      </el-form-item>

      <el-form-item label="请求头">
        <el-button size="small" @click="addHeader">添加请求头</el-button>
        <div v-for="(header, index) in formData.headers" :key="index" style="margin-top: 10px;">
          <el-row :gutter="10">
            <el-col :span="10">
              <el-input v-model="header.key" placeholder="Key" />
            </el-col>
            <el-col :span="10">
              <el-input v-model="header.value" placeholder="Value" />
            </el-col>
            <el-col :span="4">
              <el-button type="danger" size="small" @click="removeHeader(index)">删除</el-button>
            </el-col>
          </el-row>
        </div>
      </el-form-item>

      <el-form-item label="请求参数">
        <el-tabs v-model="paramTab">
          <el-tab-pane label="Query参数" name="query">
            <el-button size="small" @click="addQueryParam">添加参数</el-button>
            <div v-for="(param, index) in formData.query_params" :key="index" style="margin-top: 10px;">
              <el-row :gutter="10">
                <el-col :span="10">
                  <el-input v-model="param.key" placeholder="Key" />
                </el-col>
                <el-col :span="10">
                  <el-input v-model="param.value" placeholder="Value" />
                </el-col>
                <el-col :span="4">
                  <el-button type="danger" size="small" @click="removeQueryParam(index)">删除</el-button>
                </el-col>
              </el-row>
            </div>
          </el-tab-pane>

          <el-tab-pane label="Body参数" name="body">
            <el-input
              v-model="formData.body"
              type="textarea"
              :rows="8"
              placeholder="请输入JSON格式的Body参数"
            />
          </el-tab-pane>
        </el-tabs>
      </el-form-item>

      <el-form-item label="描述">
        <el-input
          v-model="formData.description"
          type="textarea"
          :rows="3"
          placeholder="请输入用例描述"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  title: {
    type: String,
    default: '编辑测试用例'
  },
  caseData: {
    type: Object,
    default: () => ({})
  },
  projects: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['update:modelValue', 'submit'])

const visible = ref(props.modelValue)
const formRef = ref(null)
const paramTab = ref('query')

const formData = reactive({
  name: '',
  project_id: null,
  method: 'GET',
  path: '',
  headers: [],
  query_params: [],
  body: '',
  description: ''
})

const rules = {
  name: [{ required: true, message: '请输入用例名称', trigger: 'blur' }],
  project_id: [{ required: true, message: '请选择项目', trigger: 'change' }],
  method: [{ required: true, message: '请选择请求方法', trigger: 'change' }],
  path: [{ required: true, message: '请输入请求路径', trigger: 'blur' }]
}

watch(() => props.modelValue, (val) => {
  visible.value = val
})

watch(() => props.caseData, (val) => {
  if (val && Object.keys(val).length > 0) {
    Object.assign(formData, {
      name: val.name || '',
      project_id: val.project_id || null,
      method: val.method || 'GET',
      path: val.path || '',
      headers: val.headers || [],
      query_params: val.query_params || [],
      body: typeof val.body === 'string' ? val.body : JSON.stringify(val.body || {}, null, 2),
      description: val.description || ''
    })
  }
}, { immediate: true, deep: true })

const addHeader = () => {
  formData.headers.push({ key: '', value: '' })
}

const removeHeader = (index) => {
  formData.headers.splice(index, 1)
}

const addQueryParam = () => {
  formData.query_params.push({ key: '', value: '' })
}

const removeQueryParam = (index) => {
  formData.query_params.splice(index, 1)
}

const handleClose = () => {
  emit('update:modelValue', false)
}

const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    
    // 验证Body是否为有效JSON
    if (formData.body) {
      try {
        JSON.parse(formData.body)
      } catch (e) {
        ElMessage.error('Body参数必须是有效的JSON格式')
        return
      }
    }
    
    emit('submit', { ...formData })
    handleClose()
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}
</script>

<style scoped>
.el-row {
  margin-bottom: 10px;
}
</style>
